package com.ljkj.cordial.chat.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.dto.FriendDto;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.MsgType;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.dao.notify.BusinessLeaveTable;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.ui.AppEventActivity;
import com.ljkj.cordial.chat.ui.views.ApplyFriendView;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.nic.view.util.JToast;
import com.nic.view.widget.CircleImageView;
import com.nic.view.widget.ContainsEmojiEditText;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 好友申请
 */
public class ApplyFriendActivity extends AppEventActivity<ApplyFriendView> {

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_append_info)
    TextView tvAppendInfo;
    @BindView(R.id.tv_no)
    TextView tvNo;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    @BindView(R.id.iv_avatar)
    CircleImageView ivAvatar;
    @BindView(R.id.tv_group_name)
    TextView tvGroupName;
    @BindView(R.id.ll_group_hint)
    LinearLayout llGroupHint;
    @BindView(R.id.iv_is_visitor)
    ImageView ivIsVisitor;
    @BindView(R.id.et_refuse_reason)
    ContainsEmojiEditText etRefuseReason;

    private BusinessLeaveTable info;
    private int chatType;

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_apply_friend;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        info = (BusinessLeaveTable) getIntent().getSerializableExtra(Canstants.KEY_LEAVE_INFO);
        if (info != null) {
            chatType = info.getTargetStatus();
            switch (chatType) {
                //消息类型为5，INVITE_TOURISTS,群主邀请游客用户的消息
                case IMSContacts.MsgContentType.INVITE_TOURISTS:
//                    setApplyGroup("入群邀请");
//                    break;
                    //消息类型为6，INVITE_REGISTERED，群主邀请注册用户的消息
                case IMSContacts.MsgContentType.INVITE_REGISTERED:
                    setApplyGroup("入群邀请");
                    break;

                //消息类型为9，APPLY_TOURISTS,游客用户申请入群的消息
                case IMSContacts.MsgContentType.APPLY_TOURISTS:
                    ivIsVisitor.setVisibility(View.VISIBLE);
                    setApplyGroup("申请入群");
                    break;
                //消息类型为10，APPLY_REGISTERED，注册用户申请入群的消息
                case IMSContacts.MsgContentType.APPLY_REGISTERED:
                    setApplyGroup("申请入群");
                    break;

                //消息类型13，游客用户好友申请
                case IMSContacts.MsgContentType.APPLY_FRIEND_TOURISTS:
                    ivIsVisitor.setVisibility(View.VISIBLE);
                    setApplyFriend();
                    break;
                //消息类型14，注册用户好友申请
                case IMSContacts.MsgContentType.APPLY_FRIEND_REGISTERED:
                    setApplyFriend();
                    break;
            }
        }
    }

    private void setApplyFriend() {
        getToolbar().setTitle("好友申请");
        tvName.setText(info.getTargetUserName());
        tvId.setText(info.getTargetUserId());
        tvAppendInfo.setText(info.getTargetLeave());
        if (!TextUtils.isEmpty(info.getAvatarUrl())) {
            AlbumManageUtil.getInstance().downLoadFileFriend(info.getAvatarUrl(), tvId.getText().toString(), ivAvatar);
        }
    }

    private void setApplyGroup(String 入群邀请) {
        getToolbar().setTitle(入群邀请);
        llGroupHint.setVisibility(View.VISIBLE);
        if (info != null) {
            tvName.setText(info.getTargetUserName());//群主
            tvId.setText("ID:" + info.getTargetUserId());
            tvGroupName.setText(info.getTargetGroupName());
            tvAppendInfo.setText(info.getTargetLeave());
            if (!TextUtils.isEmpty(info.getAvatarUrl())) {
                AlbumManageUtil.getInstance().downLoadFileFriend(info.getAvatarUrl(), info.getTargetUserId(), ivAvatar);
            }
        }
    }

    public static void jumpTo(Activity activity, BusinessLeaveTable table) {
        Intent intent = new Intent(activity, ApplyFriendActivity.class);
        intent.putExtra(Canstants.KEY_LEAVE_INFO, table);
        activity.startActivityForResult(intent, Canstants.KEY_APPLY_AGREE_RESULT);
    }

    @OnClick({R.id.tv_no, R.id.tv_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_no:
                String refuseReason = "";
                if (!TextUtils.isEmpty(etRefuseReason.getText()))
                    refuseReason = etRefuseReason.getText().toString();
                if (null != obtainView() && null != info) {
                    if (chatType == IMSContacts.MsgContentType.APPLY_FRIEND_TOURISTS || chatType == IMSContacts.MsgContentType.APPLY_FRIEND_REGISTERED) {
                        obtainView().doRefuseFriend(info.getTargetUserId(), info.getTargetUserName(), info.getAvatarUrl(), info.getTargetUserType(), refuseReason);
                    } else {
                        obtainView().doRefuseGroup(info.getTargetGroupId(), info.getTargetGroupName(), info.getTargetUserId(), refuseReason);
                    }
                }
                break;
            case R.id.tv_ok:
                if (null != obtainView() && null != info) {
                    if (chatType == IMSContacts.MsgContentType.APPLY_FRIEND_TOURISTS || chatType == IMSContacts.MsgContentType.APPLY_FRIEND_REGISTERED) {
                        obtainView().doAgreeFriend(info.getTargetUserId(), info.getTargetUserName(), info.getAvatarUrl(), info.getTargetUserType());
                    } else {
                        obtainView().doAgreeGroup(info.getTargetGroupId(), info.getTargetUserId());
                    }
                }
                break;
        }
    }

    @Override
    protected ApplyFriendView bindNettyMessageView() {
        return new ApplyFriendView(new ApplyFriendView.ApplyFriendCallback() {
            @Override
            public void onAgreeCallback(int code, String msg, FriendDto data) {
                if (code == IMSContacts.ResponseCode.SUCCESS) {
                    ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Object>() {
                        @Override
                        public void onAction(Object obj) {
                            MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.DELETE_FRIEND);
                            EventBus.getDefault().post(event);
                            setResult(Canstants.KEY_APPLY_AGREE_RESULT);
                            finish();
                        }

                        @Override
                        public Object onThreadAction() {
                            FriendTable table = FriendTable.getTableByFriendUserId(info.getTargetUserId());
                            if (table == null) table = new FriendTable();
                            table.setFriendUserId(ApplyFriendActivity.this.info.getTargetUserId());
                            table.setFriendNickname(ApplyFriendActivity.this.info.getTargetUserName());
                            table.setFriendAvatar(ApplyFriendActivity.this.info.getAvatarUrl());
                            table.setUserType(ApplyFriendActivity.this.info.getTargetUserType());
                            table.setOfflineMessage(true);
                            FriendTable.insert(table);
                            insertChatMainFriend(table);
                            DbController.getInstance().getWrite().delete(info);
                            return null;
                        }
                    });
                } else {
                    if (TextUtils.isEmpty(msg)) msg = "服务端异常，消息发送失败";
                    JToast.showShort(ApplyFriendActivity.this, msg);
                }
            }

            @Override
            public void onRefuseCallback(int code, String msg) {
                if (code != IMSContacts.ResponseCode.SUCCESS) {
                    if (TextUtils.isEmpty(msg)) msg = "服务端异常，消息发送失败";
                    JToast.showShort(ApplyFriendActivity.this, msg);
                    return;
                }
                DbController.getInstance().getWrite().delete(info);
                finish();
            }

            @Override
            public void onGroupAgreeCallback(int code, String msg) {
                if (code != IMSContacts.ResponseCode.SUCCESS) {
                    if (TextUtils.isEmpty(msg)) msg = "服务端异常，消息发送失败";
                    JToast.showShort(ApplyFriendActivity.this, msg);
                    return;
                }
                DbController.getInstance().getWrite().delete(info);
                finish();
            }

            @Override
            public void onGroupRefuseCallback(int code, String msg) {
                if (code != IMSContacts.ResponseCode.SUCCESS) {
                    if (TextUtils.isEmpty(msg)) msg = "服务端异常，消息发送失败";
                    JToast.showShort(ApplyFriendActivity.this, msg);
                    return;
                }
                DbController.getInstance().getWrite().delete(info);
                finish();
            }
        });
    }

    public void insertChatMainFriend(FriendTable friendTable) {
        ChatContentTable chatTableBean = ChatContentTable.queryRowByTargetIdNotNull(friendTable.getFriendUserId(), Canstants.SINGLE_CHAT);
        chatTableBean.setIsTOP(0);
        chatTableBean.setChatType(Canstants.SINGLE_CHAT);
        chatTableBean.setTargetId(friendTable.getFriendUserId());
        chatTableBean.setTargetName(TextUtils.isEmpty(friendTable.getFriendAlias()) ? friendTable.getFriendNickname() : friendTable.getFriendAlias());
        chatTableBean.setTargetType(friendTable.getUserType());
        chatTableBean.setTargetAvatarUrl(friendTable.getFriendAvatar());
        chatTableBean.setUpdateTime(System.currentTimeMillis());
        chatTableBean.setLastMsgType(MsgType.Text);
        chatTableBean.setLastMsg(String.format(getResources().getString(R.string.Apply_Friend), chatTableBean.getTargetName()));
        chatTableBean.setIsRead(0);
        chatTableBean.setMsgNum(1);
        ChatContentTable.insert(chatTableBean);

    }
}
